<script setup>
import { watch, ref, toRefs, computed, onMounted } from 'vue'
import * as jsonlint from 'json-lint'
window['jsonlint'] = jsonlint
import CodeMirror from 'codemirror'
import 'codemirror/addon/lint/lint.css'
import 'codemirror/addon/fold/foldgutter.css'
import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/rubyblue.css'
import 'codemirror/mode/javascript/javascript'
import 'codemirror/addon/lint/lint'
import 'codemirror/addon/lint/json-lint'

// 折叠
import 'codemirror/addon/fold/foldgutter.css'
import 'codemirror/addon/fold/foldcode'
import 'codemirror/addon/fold/foldgutter'
import 'codemirror/addon/fold/brace-fold'
import 'codemirror/addon/fold/comment-fold'

const code = ref('')
const jsonEditor = ref()
const myCodeRef = ref()
const props = defineProps({
	modelValue: {
		type: String,
		required: false,
		default: ''
	}
})

const emit = defineEmits(['update:modelValue'])
const { modelValue } = toRefs(props)

watch(
	() => modelValue.value,
	val => {
		code.value = val
		const editorValue = jsonEditor.value.getValue()
		if (val !== editorValue) {
			jsonEditor.value.setValue(JSON.stringify(this.value, null, 2))
		}
	},
	{
		immediate: true,
		deep: true
	}
)

watch(
	() => code.value,
	val => {
		emit('update:modelValue', val)
	}
)

onMounted(() => {
	jsonEditor.value = CodeMirror.fromTextArea(myCodeRef.value, {
		lineNumbers: true, // 是否显示行数
		mode: 'application/json', // 接受的类型，json xml....
		gutters: ['CodeMirror-lint-markers'], // 样式的宽度
		theme: 'rubyblue', // 主题
		lint: true
	})
	jsonEditor.value.setValue(JSON.stringify(this.value, null, 2))
	jsonEditor.value.on('change', fm => {
		const test1 = fm.getValue()
		console.log(test1)
	})
})
</script>

<template>
	<div class="json-editor">
		<textarea ref="myCode" class="textarea"></textarea>
	</div>
</template>

<style lang="scss">
.CodeMirror {
	height: 100vh;
	overflow: hidden;
}
</style>
